<?php


namespace app\merchant\controller\system;

use app\common\cache\utils\CaptchaSmsCache;
use app\common\controller\BaseController;
use app\common\service\merchant\MerchantService;
use app\common\service\promotion\PromotionUserService;
use app\common\service\utils\SmsUtils;
use app\common\validate\merchant\MerchantValidate;
use app\common\service\system\SettingService;
use hg\apidoc\annotation as Apidoc;

/**
 * @Apidoc\Title("注册")
 * @Apidoc\Group("logout")
 * @Apidoc\Sort("100")
 */
class Register extends BaseController
{
    /**
     * @Apidoc\Title("手机注册验证码")
     * @Apidoc\Query("mer_phone", type="string", require=true, desc="手机", mock="@phone")
     * @Apidoc\NotHeaders()
     * @Apidoc\NotQuerys()
     * @Apidoc\NotParams()
     */
    public function phoneCaptcha()
    {
        $setting = SettingService::info('mer_phone_register');
        if (!$setting['mer_phone_register']) {
            return error('系统维护，无法注册');
        }
        $param = $this->params(['mer_phone/s' => '']);
        validate(MerchantValidate::class)->scene('phoneRegisterCaptcha')->check($param);
        SmsUtils::captcha($param['mer_phone']);
        return success($param, '发送成功');
    }
    /**
     * @Apidoc\Title("商家注册")
     * @Apidoc\Query("mer_phone", type="string", require=true, desc="手机", mock="@phone")
     * @Apidoc\NotHeaders()
     * @Apidoc\NotQuerys()
     * @Apidoc\NotParams()
     */
    public function register()
    {
        $param = $this->params([
            'mer_phone/s'        => '',
            'invitation_code/s'     => '',
            'mer_pwd/s'     => '',
            'verification_code/s' => '',
        ]);
        /******************************手机验证码 验证***********************************/
        validate(MerchantValidate::class)->scene('register')->check($param);
        $setting = SettingService::info('mer_phone_register');
        if ($setting['mer_phone_register'] == 1) {
            if (empty($param['verification_code'])) {
                return error('请输入验证码');
            }
            $captcha = CaptchaSmsCache::get($param['mer_phone']);
            if ($captcha != $param['verification_code']) {
                return error('验证码错误');
            }
            CaptchaSmsCache::del($param['mer_phone']);
        }
        /******************************邀请码处理***********************************/
        if($param['invitation_code']){
            $promotion_user_id=PromotionUserService::getUserIdByCode($param['invitation_code']);
            $param['promotion_user_id'] =$promotion_user_id;
        }
        $param['mer_account'] = $param['mer_phone'];
        unset($param['verification_code'],$param['invitation_code']);
        $data = MerchantService::add($param);
        unset($data['mer_pwd']);
        return success($data, '注册成功');
    }
}
